//
//  WmcHomeVC+Business.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/5/14.
//

import UIKit
import YPBedrock

// MARK: - 业务相关

extension WmcHomeVC {
    /// 拍照得积分的气泡
    func showTakePhotoBubble() {
        let title = "拍照得积分"
        guard bubbleViewMap[title] == nil else { return } // 拦截多次创建气泡
        WmcTrack.addEvent(id: "SA0301")
        let bubbleVM = WmcBubbleVM()
        let takeAttStr = title.yp.makeAttributed { make in
            let prefixRange = 0 ..< 3
            make.set(foregroundColor:UIColor.white, range: prefixRange)
            make.set(font: 14.wmc_font, range: prefixRange)
            let suffixRange = 3 ..< 5
            make.set(foregroundColor:UIColor.wmc_yellow_FFC400, range: suffixRange)
            make.set(font: 14.yp.uiFont(weight: .bold), range: suffixRange)
        }
        let imageConfig: WmcBubbleVM.ContentStyle.ImageConfig = .init(size: 20.yp.cgSize, contentMode: .scaleAspectFit)
        let config: WmcBubbleVM.ContentStyle.ImageTextConfig = .init(imageConfig: imageConfig, imageTextSpacing: 4)
        bubbleVM.contentStyle = .imageAttributedText(image: "business_integral".wmc_image,
                                                     attributedText: takeAttStr,
                                                     style: .imageLeftTextRight,
                                                     config: config)
        bubbleVM.bubbleSize = CGSize(width: 115, height: 32)
        bubbleVM.contentCornerRadius = 16
        bubbleVM.markView = footerView.actionBtn
        bubbleVM.showInView = view
        let bubbleView = WmcBubbleView(bubbleVM)
        bubbleView.show()
        // 添加到表
        bubbleViewMap[title] = bubbleView
    }

    /// 移除气泡
    func hideTakePhotoBubble() {
        let title = "拍照得积分"
        guard let bubbleView = bubbleViewMap[title] else { return }
        bubbleView.dismiss()
        bubbleViewMap.removeValue(forKey: title)
    }

    /// 展示挽留弹窗
    func showRetainAlert(_ leaveBlock: @escaping YPBlock.Empty,
                         lawyerVideoBlock: @escaping YPBlock.Empty)
    {
        let alert = WmcRetainAlertView()
        alert.show()
        WmcTrack.addEvent(id: "SA0302")
        // 律师
        alert.lawyerVideoBtn.yp.addEvent { _ in
            WmcTrack.addEvent(id: "SA0310")
            lawyerVideoBlock()
        }
        // 离开
        alert.leaveBtn.yp.addEvent { _ in
            WmcTrack.addEvent(id: "SA0303")
            leaveBlock()
        }
        // 继续
        alert.continueBtn.yp.addEvent { [weak alert] _ in
            guard let weakAlert = alert else { return }
            WmcTrack.addEvent(id: "SA0304")
            weakAlert.dismiss()
        }
    }

    /// 弹窗挽留事件
    func retainAlertBack() {
        // 还在签到时间内
        if viewModel.business_punchCardDayNumRelay.value < 3 {
            showRetainAlert { // 狠心离开
                YPApp.CurrentVC?.dismiss(animated: true, completion: {
                    YPWmcManager.dismiss()
                })
            } lawyerVideoBlock: { // 律师视频
                YPApp.CurrentVC?.dismiss(animated: true, completion: { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.pushLawyerVideo()
                })
            }
        } else { // 活动已完成，直接返回不挽留
            YPWmcManager.dismiss()
        }
    }

    /// 展示打卡弹窗
    func showPunchCardAlert(_ punchCardCount: Int,
                            lawyerVideoBlock: @escaping YPBlock.Empty)
    {
        guard punchCardCount != 0 else { return }
        var height: CGFloat = 370
        if punchCardCount >= 3 {
            height = 350
        }
        // 外部索要提示文案
        let alert = WmcPunchCardAlertView(currentPunchCardCount: punchCardCount)
        if let promptText = YPWmcManager.shared.delegate.a_giveIntegralDelegate?.punchCardPrompt(.current,
                                                                                                 punchCardCount: punchCardCount)
        {
            alert.promptLabel.text = promptText
        }
        alert.show(height: height)

        if punchCardCount >= 3 {
            WmcTrack.addEvent(id: "SA0305")
        } else {
            WmcTrack.addEvent(id: "SA0308")
        }
        // 去查看
        alert.lookBtn.yp.addEvent { _ in
            WmcTrack.addEvent(id: "SA0306")
            YPApp.CurrentVC?.dismiss(animated: true, completion: {
                YPWmcManager.dismiss() {
                    // 事件外抛
                    YPWmcManager.shared.delegate.a_giveIntegralDelegate?.didSelectGoSeeIt(.current,
                                                                                          punchCardCount: punchCardCount)
                }
            })
        }
        // 看视频
        alert.lawyerVideoBtn.yp.addEvent { _ in
            WmcTrack.addEvent(id: "SA0312")
            lawyerVideoBlock()
        }
        // 继续
        alert.continueBtn.yp.addEvent { [weak alert] _ in
            guard let weakAlert = alert else { return }
            if punchCardCount >= 3 {
                WmcTrack.addEvent(id: "SA0307")
            } else {
                WmcTrack.addEvent(id: "SA0309")
            }
            weakAlert.dismiss()
        }
    }

    /// 推出律师视频
    func pushLawyerVideo() {
        guard let videoInfo = viewModel.business_integralRelay.value?.videoInfo else { return }
        let vm = WmcVideoPlayerVM()
        vm.title = videoInfo.videoName
        vm.taskUrlStringlist = [videoInfo.videoUrl]
        vm.viewWillAppearBlock = {
            WmcTrack.addEvent(id: "SA0313")
        }
        vm.viewDidDisappearBlock = {
            WmcTrack.addEvent(id: "SA0314")
        }
        WmcNavigatorManager.push(.videoPlayer, style: .top, parms: vm)
    }

    /// 绑定业务的监听
    func bindViewModelBusiness() {
        // 资格
        viewModel.business_integralRelay.subscribe(onNext: { [weak self] integralModel in
            guard let weakSelf = self else { return }
            if integralModel?.tip == 1 { // 有资格，展示弹窗
                weakSelf.showTakePhotoBubble()
            } else { // 无资格，隐藏弹窗
                weakSelf.hideTakePhotoBubble()
            }
        }).disposed(by: rx.disposeBag)

        // 打卡天数
        viewModel.business_punchCardDayNumRelay.subscribe(onNext: { [weak self] num in
            guard let weakSelf = self else { return }
            weakSelf.showPunchCardAlert(num) { // 展示打卡
                YPApp.CurrentVC?.dismiss(animated: true, completion: { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.pushLawyerVideo()
                })
            }
        }).disposed(by: rx.disposeBag)
    }
    
    func updateSyncStatus() {
        if !WmcLoginManager.shared.isLogin {
            footerView.updateSyncTeamStatus(count: 0)
            return
        }
        WmcPreferenceSettingsManager.fetchTeamSyncCount { [weak self] count in
            guard let weakSelf = self else { return }
            weakSelf.footerView.updateSyncTeamStatus(count: count)
        }
    }
    
    func updateCloudAlbumRedPoint() {
        // 查询相册是否显示小红点
        viewModel.fetchCloudAblumRedPoint { [weak self] isShow in
            guard let weakSelf = self else { return }
            weakSelf.footerView.cloudAlbumBtn.setRedPointDisplay(isShow)
        }
    }
}
